<template>
  <div class="yly-upload">
    <van-field :name="name" required :label="label">
      <template #input>
        <div />
      </template>
    </van-field>
    <div class="upload-content">
      <van-uploader v-model="fileList" :max-count="maxCount" :before-read="beforeRead" :after-read="afterRead" preview-full-image @oversize="onOversize"/>
      <div class="tip">{{ tip }}</div>
    </div>
  </div>
</template>

<script>
import { Field, Uploader, Toast } from 'vant'
// import { commonService } from '@/services'
import { postHandle, getHandle } from '@/api'
import { filePath } from '../filters'
import qs from 'qs'
export default {
  name: 'YlyUploader',
  components: {
    [Field.name]: Field,
    [Uploader.name]: Uploader
  },
  props: {
    value: {
      type: Array
    },
    required: {
      type: Boolean,
      default: false
    },
    name: {
      type: String
    },
    label: {
      type: String,
      default: '图片'
    },
    tip: {
      type: String,
      default: '注：支持格式JPG、JPEG、PNG，最多上传3张照片，单个不超过5M'
    },
    maxCount: {
      type: Number,
      default: 3
    },
    maxSize: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  watch: {
    value(val) {
      if (val && val.length > 0) {
        val.forEach(item => {
          item.url = filePath(item.fileId, 's')
          item.isImage = true
        })
        this.fileList = val
      }
    }
  },
  mounted() {
    if (this.value && this.value.length > 0) {
      this.value.forEach(item => {
        item.url = filePath(item.fileId, 's')
        item.isImage = true
      })
      this.fileList = this.value
    }
  },
  methods: {
    onOversize(file) {
      console.log(file)
      Toast('文件大小不能超过 500kb')
    },
    beforeRead(file) {
      if (file.size > this.maxSize * 1024 * 1024) {
        Toast('上传文件不能大于' + this.maxSize + 'M')
        return false
      }
      return true
    },
    afterRead(file) {
      file.status = 'uploading'
      file.message = '上传中...'
      this.compress(file.file, res => {
        const data = res.body.fileStorage
        file.url = `/ccyt/api/show/${data.name}_s`
        file.fileId = data.name
        file.name = data.filename
        file.suffix = data.suffix
        file.size = data.size
        file.status = 'success'
        file.message = '上传成功'
        this.$emit('input', this.fileList.map(item => {
          return {
            name: item.name,
            size: item.size,
            regex: item.regex,
            fileId: item.fileId
          }
        }))
      })
    },
    compress(file, callback) {
      const fileObj = file
      const reader = new FileReader()
      reader.readAsDataURL(fileObj) // 转base64
      reader.onload = function(e) {
        const image = new Image() // 新建一个img标签（还没嵌入DOM节点)
        image.src = e.target.result
        image.onload = function() {
          const canvas = document.createElement('canvas') // 新建canvas
          const context = canvas.getContext('2d')
          const imageWidth = image.width // 压缩后图片的大小
          const imageHeight = image.height
          canvas.width = imageWidth
          canvas.height = imageHeight
          context.drawImage(image, 0, 0, imageWidth, imageHeight)
          const base64 = canvas.toDataURL('image/jpeg', 0.5) // 压缩后质量
          let datas = {
              imageData: base64,
              appId: 'ccyt'
          }
          postHandle('/fms/api/uploadByBase64Data',qs.stringify(datas)).then(res => {
            callback(res)
          })
          // commonService.uploadByBase64Data({
            
          // }).then(res => {
          //   callback(res)
          // })

          // callback(files); // 回调
          // service.postHandle(
          //     '/api/fms/uploadByBase64Data',
          //     {
          //       appId: 'app018',
          //       imageData: base64
          //     },
          //     res => {
          //       callback(res);
          //     }
          // );
        }
      }
      console.log(reader,'888')
    }
  }
}
</script>

<style lang="scss" scoped>
.yly-upload {
  .van-cell::after {
    border-bottom: 0px;
  }
  .upload-content {
    background-color: #FFFFFF;
    padding: 0 15px 10px 15px;
    .tip {
      margin-top: 15px;
      color: #999999;
      font-size: 12px;
      line-height: 16px;
    }
  }
}
</style>
